

import requests,time
from config import * 
import pandas as pd

from openai import OpenAI




class LmDeepSeekApi:
    def __init__(self):
        self.base_url = "http://172.16.10.86:1234/v1"
        self.default_pre_text = "你是一名有用的助手"
        self.default_ask_text = "你是谁？"
        self.model_name = "deepseek-r1-distill-llama-8b"
        # self.chat = "http://172.16.10.86:1234/v1/chat/completions"
        # self.embedding = "http://172.16.10.86:1234/v1/embeddings"
       


    def get_models_list(self):
        response = requests.get(self.base_url + "/models")

        models_list = []
        for model in response.json()['data']:
            models_list.append(model['id'])
        return models_list
       


    def chat_completions(self):
        t0 = time.time()
        # Point to the local server
        client = OpenAI(base_url=self.base_url, api_key="lm-studio")

        completion = client.chat.completions.create(
        model=self.model_name,
        
        temperature=0.7,
        messages=[
            {"role": "system", "content": f"{self.default_pre_text}"},
            {"role": "user", "content": f"{self.default_ask_text}"}
        ],
        )
        
        # print(completion.choices[0].message.content)

        t1 = time.time()
        ask_id = completion.id
        create_unix = completion.created
        model_name = completion.model
        tokens = completion.usage.total_tokens
        message = completion.choices[0].message.content
        
        print("耗时:", t1-t0)
        res_df = pd.DataFrame({'ask_id': [ask_id], 
                               'create_unix': [create_unix],
                               'model_name': [model_name], 
                               'tokens': [tokens],
                               "pre_text":[self.default_pre_text],
                               "ask_text":[self.default_ask_text],
                               'message': [message],
                               'use_time':[t1 - t0],
                               'write_time': [time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())]})


        print("ask_id:" , "Message:", message)
        # 数据存储到数据库
        res_df.to_sql('local_deep_seek_api_res', con25, if_exists='append', index=False)
        return message
    


    

    
       
        

        

        
        
    
        
    


    # if __name__ == "__main__":
        
    #     while True:
    #         str_ask_input = input("You:")
    #         local_deep_seek_api(str_ask_input)




